
use "${data}ACS_Mexcensus_combined.dta", clear  				

*REGRESSION : TABLE 3 

  
global option varlabels tex plain fragment bdec() se starloc(1) starlevels(10 5 1) nocenter ///
		summstat(r2\N) summtitle("R^2" \"Observations") summdec(3 0) blankrows 
	
	global m3 i.birthyr  i.yedu 
	global model_3	   "Birth cohort dummies", "Y" \"Years of Education dummies", "Y"
	
	global T married_inUS 

		outreg,clear (dep_final)
		
foreach outcome in spouse_age spouse_older  spouse_yedu  spouse_moredu   spouse_USborn spouse_lang_nospan  {	
		
		
		local labout : variable label `outcome'			
		
		* all sample 
		tempvar samplee
		g `samplee' =   yedu !=. & birthyr !=. & spouse_age !=. & spouse_older!=. &  spouse_yedu!=. & ///
						spouse_moredu !=.   &  spouse_USborn!=. & spouse_lang_nospan!=.
		
		quietly{
		count if datasource=="Mexcens2020" & `samplee'==1 
		local N_cont=  r(N)  
		count if datasource=="ACS" & `samplee'==1 
		local N_marriedUS=  r(N) 
	
		}
		
		qui su `outcome' if `samplee'==1 & datasource=="Mexcens2020" 
		local av: di %4.3f r(mean)	

	     qui reg  `outcome' $T  ${m3} if `samplee' ==1 , robust 	
	 
	    qui outreg, merge(dep_final) nod keep($T) ctitle("Dep:","`labout'" )  ///
		addrows( "","" \  "Average outcome in control group", `av' \  "${model_3}" \ "N: Mexcens","`N_cont'" \ "N: ACS married aft. ","`N_marriedUS'" )  ${option} 		
		}	
	

		outreg using "${result}Table3.smcl" , title(Table 3: Migration and spouse characteristics) replace replay(dep_final) ${option} 
		
		
	

	
	
	* TABLE 4: ANALYSIS OF VARIANCE 

	
	cap drop e 
	qui reg spouse_yedu  married_inUS i.birthyr i.yedu  
	predict  e , residuals
	
	foreach v in spouse_age spouse_yedu   spouse_USborn  {
	
	qui reg `v' i.birthyr i.yedu if married_inUS==1
	predict  RES_`v'_mig	 if married_inUS==1 , residuals
	
	qui reg `v' i.birthyr i.yedu if datasource=="Mexcens2020" 
	predict  RES_`v'_stay    if datasource=="Mexcens2020"    , residuals
	}
	
	mat define V2= [.,.,.]
	
	foreach v in spouse_age spouse_yedu   spouse_USborn {
		
		qui  su RES_`v'_mig 
		local a: di %4.3f r(sd)^2
		qui  su RES_`v'_stay 
		local b: di %4.3f r(sd)^2
		
		qui  sdtest  RES_`v'_mig =   RES_`v'_stay 
		local c=r(p)
		
		mat  V2 = V2 \[`b',`a',`c']
	}
	*
	mat colnames V2=  stayer migrant test 
	
	log close _all
	log using  "${result}Table4.smcl", replace 
	mat list V2 
	log off
	log close _all
	
	